<?php
namespace app\model\auth;

use think\Model;
use think\model\concern\SoftDelete;
use app\helper\Hierarchy;

/*
 * 权限模型.
 *
 * @property integer $id
 */
class Menu extends Model
{
    protected $table = 'auth_menu';      // 表名

    /*
     * @inheritdoc
     */
    protected $field = [
		'name',
		'title',
        'pid',
        'path',
		'component',
		'perm',
        'icon',
        'is_render'
    ];
    /**
     * 名称搜索
     *
     * @param [type] $query
     * @param [type] $value
     * @param [type] $data
     * @return void
     */
    public function searchTitleAttr($query, $value, $data)
    {
        !empty($value) && $query->where('title', $value);
    }
    public function children(){
        return $this->hasMany(self::class, 'pid');
    }
    public function perm(){
        return $this->belongsTo(Perm::class, 'perm')->bind(['perm_name' => 'name']);
    }
    public static function tree(){
        $tree = cache('MenuTree');
        //if(!$tree){
            $rows = self::field([
                    'id',
                    'name',
                    'title',
                    'pid' => 'parentId',
                    'path',
                    'component',
                    'perm' => 'access',
                    'icon',
                    'IF(`is_render`>0, true, false) as renderMenu'
                ])->select()->toArray();
            Hierarchy::init($rows, ['label' => 'title', 'pid' => 'parentId']);
            $tree = Hierarchy::tree();
            cache('MenuTree', $tree);
        //}
        return $tree;
    }
}
